package train

import (
	"gin-base/base/config"
	"gin-base/base/db"
	"gin-base/common/models/userHeart"
	"gin-base/common/utils/paging"
	"github.com/jinzhu/gorm"
	"time"
)

type Record struct {
	UserId      uint
	StartAt     time.Time
	EndAt       time.Time
	SportType   int
	Distance    float64
	HeartRate   int
	Length      int
	Pace        int
	Calorie     int
	Speed       float64
	Data        string
	IsTest      int
	RecordRange RecordRange
	gorm.Model
}

func (Record) TableName() string {
	return config.Ini.String("mysql.table_prefix") + "train_record"
}

func (this *Record) Save() bool {
	db := db.Open()
	defer db.Close()

	db.Create(&this)

	return !db.NewRecord(this)
}

func (this *Record) SetRecordRange() bool {
	db := db.Open()
	defer db.Close()

	db.Model(&this).Related(&this.RecordRange, "RecordRange")

	return !db.NewRecord(this.RecordRange)
}

func GetRecords(options map[string]interface{}, pageNum int) ([]Record, interface{}) {
	db := db.Open()
	defer db.Close()

	//查询
	query := db.Model(&Record{})

	//获取总记录数
	var totalCount int
	query.Count(&totalCount)

	//分页设置
	if pageNum > 0 {
		pageNum = pageNum - 1
	}
	pageSize := paging.DefaultApiPageSize
	query = query.Limit(pageSize).Offset(pageSize * pageNum)

	user, ok := options["user_id"]
	if ok {
		query = query.Where("user_id = ?", user)
	}

	query = query.Order("created_at desc")

	//获取结果
	records := []Record{}
	query.Find(&records)

	//无数据时返回
	if len(records) == 0 {
		return nil, nil
	} else {
		//获取关联区间数据
		for i, record := range records {
			db.Model(&record).Related(&records[i].RecordRange, "RecordRange")
		}
	}

	//获取分页信息
	pageInfo := paging.GetPageInfo(pageNum, totalCount, pageSize)

	return records, pageInfo
}

func GetUserRecords(user_id uint, page int) []Record {
	db := db.Open()
	defer db.Close()

	records := []Record{}

	db.Where("user_id = ?", user_id).Limit(paging.DefaultApiPageSize).Offset(paging.DefaultApiPageSize * page).Find(&records)

	if len(records) == 0 {
		return nil
	} else {
		for i, record := range records {
			db.Model(&record).Related(&records[i].RecordRange, "RecordRange")
		}
	}

	return records
}

func GetOneRecordById(Id uint64) (record Record) {
	db := db.Open()
	defer db.Close()

	db.Where("id = ?", Id).First(&record)

	if record.ID != 0 {
		record.SetRecordRange()
	}
	return record
}

type UserMonthInfo struct {
	LastMaxHeart     float64
	Count            int
	DistanceCount    float64
	LengthAvg        int
	LengthCountValid int
	CalorieCount     int
	CalorieAvg       int
	RecordRangeCount RecordRange
}

func GetUserMonthInfo(user_id uint) interface{} {
	db := db.Open()
	defer db.Close()

	records := []Record{}

	now := time.Now()
	today := now

	lastMonth := now.AddDate(0, -1, 0)

	selectParams := "user_id, start_at, end_at, sport_type, distance, heart_rate, length, pace, calorie, speed, is_test, id, created_at, updated_at, deleted_at"
	db.Select(selectParams).Where("user_id = ? ", user_id).Where("created_at BETWEEN ? AND ?", lastMonth, today).Find(&records)

	var userMonthInfo UserMonthInfo

	//总次数
	userMonthInfo.Count = len(records)
	//运动总时长
	var lengthCount int
	var lengthCountValid int

	if userMonthInfo.Count == 0 {
		//获取最近一次心率测试数据
		lastHeart := userHeart.GetOneByUserId(user_id)
		userMonthInfo.LastMaxHeart = lastHeart.Max
		return userMonthInfo
	} else {
		for i, record := range records {
			db.Model(&record).Related(&records[i].RecordRange, "RecordRange")

			//累计运动时长
			lengthCount += records[i].Length

			//累计有效训练时长（最大心率达到训练区间）
			if records[i].RecordRange.Restore > 0 || records[i].RecordRange.Burning > 0 || records[i].RecordRange.Cardiopulmonary > 0 || records[i].RecordRange.Endurance > 0 || records[i].RecordRange.Anaerobic > 0 {
				lengthCountValid += records[i].Length
			}

			//累计卡路里
			userMonthInfo.CalorieCount += records[i].Calorie

			//累计总里程
			userMonthInfo.DistanceCount += records[i].Distance

			//累计心率区间数据
			userMonthInfo.RecordRangeCount.Restore += records[i].RecordRange.Restore
			userMonthInfo.RecordRangeCount.Burning += records[i].RecordRange.Burning
			userMonthInfo.RecordRangeCount.Cardiopulmonary += records[i].RecordRange.Cardiopulmonary
			userMonthInfo.RecordRangeCount.Endurance += records[i].RecordRange.Endurance
			userMonthInfo.RecordRangeCount.Anaerobic += records[i].RecordRange.Anaerobic
		}
	}

	//计算平均每次训练运动时长
	userMonthInfo.LengthAvg = lengthCount / userMonthInfo.Count

	//设置有效运动时长
	userMonthInfo.LengthCountValid = lengthCountValid

	//计算平均每次训练消耗卡路里
	userMonthInfo.CalorieAvg = userMonthInfo.CalorieCount / userMonthInfo.Count

	//获取最近一次心率测试数据
	lastHeart := userHeart.GetOneByUserId(user_id)
	userMonthInfo.LastMaxHeart = lastHeart.Max

	return userMonthInfo
}
